# -*- coding:utf-8 -*-
from bottle import route, run, template, static_file, error, request
import json
import random
import serial
import re
from validate import loginvalidate

ser=serial.Serial()
ser.baudrate=9600
ser.port='/dev/ttyUSB0'
ser.timeout=2
ser.open()

@route('/validate', method=['POST'])
def validate():
    username = request.POST.get('username')
    userpwd = request.POST.get('userpwd')
    iflogin = loginvalidate(username,userpwd) 
    print 'iflogin:',iflogin
    return json.dumps({'result':iflogin})

@route('/')
def index():
    return template('./main.html')

@route('/init')
def init():
    ser.write('INIT\x0d')
    n=ser.inWaiting()
    fb=ser.read(n)
    if fb == '0:\r':
        res = 'success'  
    else:
        res = 'failure'  
    print 'return:',res
    return json.dumps({'result':res})

@route('/tx', method=['POST'])
def tx():
    vl=re.findall(r'\[(.+?)\]',request.POST.get('templatestr'))
    value = request.POST.get('text')
    templaten = request.POST.get('templaten')
    print templaten
    ser.write('JN ' + templaten +'\x0d')
    print vl

    for i in vl:
            ser.write('TX '+ i +' '+ value + '\x0d')
            print 'TX '+ i +' '+ value + '\x0d'

    n=ser.inWaiting()
    fb=ser.read(n)
    if '0:\r' in fb:
        result = 'success'
    else:
        result = 'failure'
    return json.dumps({'result':result})


@route('/m0')
def m0():
    ser.write('M 0\x0d')
    n=ser.inWaiting()
    fb=ser.read(n)
    if fb == '0:\r':
        res = 'success' 
    else:
        res = 'failure' 
    print 'return:',res
    return json.dumps({'result':res})

@route('/m1', method=['POST'])
def m1():
    ETtype=request.POST.get('ETtype')
    print ETtype
    ser.write('ET ' + ETtype + '\x0d')
    n=ser.inWaiting()
    fb=ser.read(n)
    if fb[-3:]=="0:\r":
        ser.write('M 1\x0d')
        n=ser.inWaiting()
        fb=ser.read(n)
        res = 'success' 
    else:
        res = 'failure' 


    print 'return:',res
    return json.dumps({'result':res})

@route('/static/<filename:path>')
def server_static(filename):
    return static_file(filename, root='./static')

@error(404)
def error404(error):
    return 'Nothing here, sorry'

run(host='0.0.0.0', port=8080, debug=True)
